<template>
    <div id="app">
        <div class="app">
            <keep-alive>
                <router-view v-if="$route.meta.keepAlive" />
            </keep-alive>
            <router-view v-if="!$route.meta.keepAlive" />
        </div>
        <!-- <img v-if="$store.state.vuex_isShowPage" class="startup-page" src="@/assets/img/download.jpg" alt="" srcset="" /> -->
    </div>
</template>

<script>
    import request from '@/router/axios';
    import { sensorsInit } from '@/utils/sa-sdk.js';

    export default {
        name: 'app',
        components: {},
        data() {
            return {
                openId: '',
                custNo: '',
                loading: null,
                isInit: false
            };
        },
        watch: {
            '$store.state.vuex_isShowPage': function () {
                if (!this.$store.state.vuex_isShowPage) {
                    this.loading && this.loading.close();
                }
            }
        },
        created() {},
        activated() {
            this.initWxConfig();
            // this.loading = this.$loading({
            //   lock: true,
            //   text: '加载中...',
            //   spinner: 'el-icon-loading',
            //   customClass: 'customClass'
            // })
        },
        methods: {
            //   初始化信息
            initInfo() {
                let isSharePage = this.$route.query.isSharePage || 0;
                let wxUserId = this.$route.query.wxUserId || sessionStorage.getItem('wxUserId') || '';
                let wxExternalUserid = this.$route.query.wxExternalUserid || sessionStorage.getItem('wxExternalUserid') || '';
                let chatId = this.$route.query.chatId || '';
                this.$store.commit('setIsSharePage', isSharePage);
                this.$store.commit('setWxUserId', wxUserId);
                this.$store.commit('setWxExternalUserid', wxExternalUserid);
                this.$store.commit('setChatId', chatId);
                if (this.$utils.isWx() && this.$utils.isMobile()) {
                    sensorsInit(this.$store.state.vuex_wxUserId, this.openId, this.custNo);
                }
            },
            // wx环境中初始化信息
            initWxConfig() {
                // 在手机微信中
                if (this.$utils.isWx() && this.$utils.isMobile()) {
                    const wxjsSdk = window.$wx16;
                    let url = this.$utils.getPageUrl().split('#/')[0].split('?');
                    let purls = `${url[0]}?${encodeURIComponent(url[1])}`;
                    if (url[1]) {
                        purls = `${url[0]}?${encodeURIComponent(url[1])}`;
                    } else {
                        purls = `${url[0]}`;
                    }

                    request({
                        url: `/cp/portal/sign?url=${purls}`,
                        method: 'post'
                    }).then((res) => {
                        let codeStr = this.$utils.getSearchString('code', location.search) || '';
                        let openId = localStorage.getItem('wxOpenId') || '';
                        if (!codeStr && !openId) {
                            window.location.replace(
                                `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.data.data.appId}&redirect_uri=${encodeURIComponent(
                                    window.location.href
                                )}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
                            );
                            // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.data.data.appId}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
                        } else {
                            // window.location.reload()
                            this.getWxUserInfo(codeStr, openId);
                            wxjsSdk.config({
                                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                appId: res.data.data.appId, // 必填，公众号的唯一标识
                                timestamp: res.data.data.timestamp, // 必填，生成签名的时间戳
                                nonceStr: res.data.data.noncestr, // 必填，生成签名的随机串
                                signature: res.data.data.signature, // 必填，签名
                                jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
                                openTagList: ['wx-open-launch-weapp', 'wx-open-launch-app']
                            });
                            wxjsSdk.ready(() => {
                                if (this.isInit) {
                                    this.initInfo();
                                } else {
                                    this.isInit = true;
                                }
                                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                            });
                            wxjsSdk.error(function (res) {
                                console.error('错误===', res);
                            });
                        }
                    });
                } else {
                    this.initInfo();
                }
            },
            // 获取微信用户信息
            getWxUserInfo(codeStr, openId) {
                request({
                    url: `/cp/portal/wxUserOpenid?code=${codeStr}&openId=${openId}`,
                    method: 'get'
                }).then((res) => {
                    console.log('获取用户信息===', res);
                    localStorage.setItem('wxOpenId', res.data.data.openId);
                    this.openId = res.data.data.openId;
                    this.custNo = res.data.data.custNo || res.data.data.openId;
                    if (this.isInit) {
                        this.initInfo();
                    } else {
                        this.isInit = true;
                    }
                    // 获取到用户信息后重置url
                    let urlArr = this.$utils.getPageUrl().split('#/');
                    history.replaceState(null, '', `/#/${urlArr[1]}`);
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
    @import './assets/css/public.css';
    #app {
        max-width: 420px;
        margin: 0 auto;
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #2c3e50;
    }
    .app {
        height: 100vh;
        overflow: auto;
        -webkit-overflow-scrolling: touch;
    }
    .startup-page {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100vh;
        z-index: 999;
    }
    .customClass {
        background: #fff;
        .el-loading-spinner {
            .el-icon-loading {
                font-size: 50px;
            }
        }
    }

    ::-webkit-scrollbar {
        display: none;
    }
</style>
